package 数组;

public class 螺旋矩阵Ⅱ {
    class  Solution{
        public int[][]  generateMatrix(int n){
            int[][] res = new int[n][n];
            //循环次数
            int loop = n/2;
            //每次循环的起始位置
            int startx = 0;
            int starty = 0;

            int count = 1;

            //偏移量
            int offest = 1;

            int mid = n/2;

            while(loop>0){
                int i = startx;
                int j = starty;
                //模拟上侧从左到右
                for (;j<n+starty-offest;++j){
                    res[startx][j] = count++;
                }
                //模拟右侧从上到下
                //这个时候的j是上一个for到最后j的值
                for (;i<n+startx-1;++i){
                    res[i][j] = count++;
                }
                for (;j>starty;j--){
                    res[i][j] = count++;
                }
                // 模拟左侧从下到上
                for (; i > startx; i--) {
                    res[i][j] = count++;
                }

                loop--;
                startx+=1;
                starty+=1;
                offest+=2;
            }
            if (n%2==1){
                res[mid][mid] = count ;
            }

            return res;
        }
    }
}
